package de.windeln.marketing.validation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import de.windeln.marketing.campaign.costinterval.services.interfaces.CostIntervalService;
import de.windeln.marketing.campaign.model.RequestClientObject;

@Component
public class CampaignIntervalRoundCostInterval implements Validator {

	@Resource(name = "costIntervalService")
	private CostIntervalService costIntervalService;

	@Override
	public boolean supports(Class<?> clazz) {
		return clazz == RequestClientObject.class;
	}

	@Override
	public void validate(Object target, Errors errors) {
		RequestClientObject rco = (RequestClientObject) target;
		List<Map<String, Object>> dates = new ArrayList<Map<String, Object>>();
		dates = costIntervalService.findAllCostintervalDatesByCampaignId(rco.getId());
		for (int i = 0; i < dates.size(); i++) {
			DateTime cost_end = new DateTime((Date) dates.get(i).get("COST_END"));
			DateTime cost_start = new DateTime((Date) dates.get(i).get("COST_START"));
			if (!(new DateTime(rco.getCampaignStart())).isBefore(cost_start) || (new DateTime(rco.getCampaignEnd()).isAfter(cost_end))) {
				errors.rejectValue("campaignStart", "Campaign Interval Round Cost Interval ", "Campaign Interval is excluding Cost Interval(s)!");
				errors.rejectValue("campaignEnd", "Campaign Interval Round Cost Interval ", "Campaign Interval is excluding Cost Interval(s)!");

			}
		}
	}

}
